<template>
  <div class="p-6 space-y-4">
    <!-- 顶部筛选栏 -->
    <el-card shadow="never">
      <div class="flex flex-wrap items-center gap-3">
        <el-input
          v-model="filters.keyword"
          placeholder="搜索 标的/描述/提出人"
          clearable
          class="w-72"
          @keyup.enter.native="
            () => {
              pager.page = 1;
              fetchList();
            }
          "
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-input
          v-model="filters.owner"
          placeholder="搜索责任人"
          clearable
          class="w-40"
          @keyup.enter.native="
            () => {
              pager.page = 1;
              fetchList();
            }
          "
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="filters.proposerDept"
          placeholder="提出部门"
          clearable
          class="w-44"
        >
          <el-option v-for="d in deptOptions" :key="d" :label="d" :value="d" />
        </el-select>

        <el-select
          v-model="filters.category"
          placeholder="问题分类"
          clearable
          class="w-52"
        >
          <el-option
            v-for="c in categoryOptions"
            :key="c"
            :label="c"
            :value="c"
          />
        </el-select>

        <el-select
          v-model="filters.status"
          placeholder="进度"
          clearable
          class="w-40"
        >
          <el-option
            v-for="s in statusOptions"
            :key="s.value"
            :label="s.label"
            :value="s.value"
          />
        </el-select>

        <el-select
          v-model="filters.ownerDept"
          placeholder="责任部门"
          clearable
          class="w-44"
        >
          <el-option v-for="d in deptOptions" :key="d" :label="d" :value="d" />
        </el-select>

        <div class="ml-auto flex gap-2">
          <el-button type="primary" @click="openEdit()"
            ><el-icon class="mr-1"><Plus /></el-icon>新建问题</el-button
          >
          <el-button
            @click="
              () => {
                pager.page = 1;
                fetchList();
              }
            "
            >搜索</el-button
          >
          <el-button
            @click="
              () => {
                Object.assign(filters, baseFilters);
                pager.page = 1;
                fetchList();
              }
            "
            >重置</el-button
          >
          <el-button type="warning" :loading="loading" @click="handleExport"
            >导出</el-button
          >
        </div>
      </div>
    </el-card>

    <!-- 数据表 + 分页 -->
    <el-card shadow="never">
      <el-table :data="rows" border stripe height="62vh" v-loading="loading">
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="status" label="进度" width="140">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)" effect="dark">{{
              statusLabel(row.status)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="proposerDept"
          label="提出部门"
          width="140"
          sortable
        />
        <el-table-column prop="proposer" label="提出人" width="120" sortable />
        <el-table-column
          prop="category"
          label="问题分类"
          width="180"
          sortable
        />
        <el-table-column
          prop="subject"
          label="问题标的"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          prop="description"
          label="问题描述"
          min-width="220"
          show-overflow-tooltip
        />
        <el-table-column prop="owner" label="责任人" width="120" sortable />
        <el-table-column
          prop="ownerDept"
          label="责任部门"
          width="160"
          sortable
        />
        <el-table-column
          prop="solution"
          label="问题解决描述"
          min-width="220"
          show-overflow-tooltip
        />
        <el-table-column prop="resolveDays" label="解决天数" width="140" />
        <el-table-column prop="createdAt" label="提出时间" width="140" />
        <el-table-column prop="completedAt" label="完成时间" width="140" />
        <el-table-column label="操作" fixed="right" width="320">
          <template #default="{ row }">
            <el-button link type="primary" @click="openDetail(row)"
              >查看</el-button
            >
            <el-button
              link
              type="primary"
              :disabled="(row.status || '').toUpperCase() !== 'WAIT'"
              :style="{
                opacity: (row.status || '').toUpperCase() !== 'WAIT' ? 0.5 : 1
              }"
              @click="openEdit(row)"
              >编辑</el-button
            >
            <el-button
              link
              type="warning"
              :disabled="(row.status || '').toUpperCase() !== 'WAIT'"
              @click="startProcessing(row)"
              >开始处理</el-button
            >
            <el-button
              link
              type="success"
              :disabled="(row.status || '').toUpperCase() === 'DONE'"
              @click="markDone(row)"
              >标记完成</el-button
            >
            <el-popconfirm
              title="确认删除该条记录？"
              @confirm="removeRow(row.id)"
            >
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-end mt-4">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50]"
          :total="pager.total"
          v-model:page-size="pager.pageSize"
          v-model:current-page="pager.page"
          @current-change="fetchList"
          @size-change="
            () => {
              pager.page = 1;
              fetchList();
            }
          "
        />
      </div>
    </el-card>

    <!-- 详情抽屉 -->
    <el-drawer
      v-model="detailVisible"
      :title="`问题详情 #${detailItem?.id ?? ''}`"
      size="50%"
    >
      <el-descriptions :column="2" border v-if="detailItem">
        <el-descriptions-item label="提出部门">{{
          detailItem.proposerDept
        }}</el-descriptions-item>
        <el-descriptions-item label="提出人">{{
          detailItem.proposer
        }}</el-descriptions-item>
        <el-descriptions-item label="问题分类">{{
          detailItem.category
        }}</el-descriptions-item>
        <el-descriptions-item label="问题标的">{{
          detailItem.subject
        }}</el-descriptions-item>
        <el-descriptions-item label="问题描述" :span="2">{{
          detailItem.description
        }}</el-descriptions-item>
        <el-descriptions-item label="责任人">{{
          detailItem.owner
        }}</el-descriptions-item>
        <el-descriptions-item label="责任部门">{{
          detailItem.ownerDept
        }}</el-descriptions-item>
        <el-descriptions-item label="进度">{{
          statusLabel(detailItem.status)
        }}</el-descriptions-item>
        <el-descriptions-item label="提出时间">{{
          detailItem.createdAt
        }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{
          detailItem.completedAt || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="问题解决描述" :span="2">{{
          detailItem.solution || "-"
        }}</el-descriptions-item>
        <el-descriptions-item label="解决天数" :span="2">{{
          detailItem.resolveDays || "-"
        }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>

    <!-- 新建/编辑弹窗 -->
    <el-dialog
      v-model="editVisible"
      :title="editForm.id ? '编辑问题' : '新建问题'"
      width="760px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="rules"
        label-width="96px"
        status-icon
      >
        <div class="grid grid-cols-2 gap-x-6">
          <el-form-item label="提出部门" prop="proposerDept">
            <el-select
              v-model="editForm.proposerDept"
              filterable
              clearable
              :disabled="isDone"
            >
              <el-option
                v-for="d in deptOptions"
                :key="d"
                :label="d"
                :value="d"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="提出人" prop="proposer">
            <el-input v-model="editForm.proposer" :disabled="isDone" />
          </el-form-item>
          <el-form-item label="问题分类" prop="category">
            <el-select
              v-model="editForm.category"
              filterable
              clearable
              :disabled="isDone"
            >
              <el-option
                v-for="c in categoryOptions"
                :key="c"
                :label="c"
                :value="c"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="问题标的" prop="subject">
            <el-input v-model="editForm.subject" :disabled="isDone" />
          </el-form-item>
          <el-form-item label="问题描述" prop="description" class="col-span-2">
            <el-input
              v-model="editForm.description"
              type="textarea"
              :disabled="isDone"
              :rows="3"
            />
          </el-form-item>
          <el-form-item label="责任人" prop="owner">
            <el-input v-model="editForm.owner" :disabled="isDone" />
          </el-form-item>
          <el-form-item label="责任部门" prop="ownerDept">
            <el-select
              v-model="editForm.ownerDept"
              filterable
              clearable
              :disabled="isDone"
            >
              <el-option
                v-for="d in deptOptions"
                :key="d"
                :label="d"
                :value="d"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="进度" prop="status">
            <el-select
              v-model="editForm.status"
              disabled
              @change="
                val => {
                  if ((val || '').toUpperCase() !== 'DONE')
                    editForm.completedAt = '';
                }
              "
            >
              <el-option
                v-for="s in statusOptions"
                :key="s.value"
                :label="s.label"
                :value="s.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="提出时间" prop="createdAt">
            <el-date-picker
              v-model="editForm.createdAt"
              type="date"
              :disabled="isDone"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
            />
          </el-form-item>
          <el-form-item label="完成时间" prop="completedAt">
            <el-date-picker
              v-model="editForm.completedAt"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
              :disabled="(editForm.status || '').toUpperCase() !== 'DONE'"
            />
          </el-form-item>
          <el-form-item label="解决描述" prop="solution" class="col-span-2">
            <el-input v-model="editForm.solution" type="textarea" :rows="2" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Search, Plus } from "@element-plus/icons-vue";
import axios from "axios";

//const apiBase = "http://localhost:44389/api/issue";
const apiBase = "http://10.0.8.42:8089/api/issue";
// const API_ISSUE_TRACKER_EXPORT =
//   "https://localhost:44389/api/issue/export-issues";
const API_ISSUE_TRACKER_EXPORT =
  "http://10.0.8.42:8089/api/issue/export-issues";

const deptOptions = ["生产", "设备", "PTE", "质量", "PE", "IT", "计划"];
const categoryOptions = [
  "prober",
  "tester",
  "针卡",
  "产品",
  "工艺工序",
  "包装",
  "UI",
  "MO"
];
const statusOptions = [
  { label: "Wait", value: "WAIT" },
  { label: "Ongoing", value: "ONGOING" },
  { label: "Done", value: "DONE" }
];

const isDone = computed(() => (editForm.status || "").toUpperCase() === "DONE");

const baseFilters = {
  keyword: "",
  proposerDept: "",
  category: "",
  status: "",
  owner: "",
  ownerDept: ""
};
const filters = reactive({ ...baseFilters });
const pager = reactive({ page: 1, pageSize: 10, total: 0 });
const loading = ref(false);
const rows = ref<any[]>([]);

function statusLabel(s: string) {
  const v = (s || "").toLowerCase();
  if (v === "ongoing") return "Ongoing";
  if (v === "done") return "Done";
  return "Wait";
}
function statusTagType(s: string) {
  const v = (s || "").toLowerCase();
  if (v === "done") return "success";
  if (v === "ongoing") return "warning";
  return "danger";
}

async function fetchList() {
  loading.value = true;
  try {
    const { data } = await axios.get(apiBase, {
      params: { ...filters, Page: pager.page, PageSize: pager.pageSize }
    });
    if (Array.isArray(data)) {
      rows.value = data;
      pager.total = data.length;
    } else {
      rows.value = data.items || [];
      pager.total = data.total ?? 0;
    }
  } finally {
    loading.value = false;
  }
}

onMounted(fetchList);

const detailVisible = ref(false);
const detailItem = ref<any | null>(null);
function openDetail(row: any) {
  detailItem.value = row;
  detailVisible.value = true;
}

const editVisible = ref(false);
const editForm = reactive<any>({
  id: 0,
  proposerDept: "",
  proposer: "",
  category: "",
  subject: "",
  description: "",
  owner: "",
  ownerDept: "",
  solution: "",
  status: "Wait",
  createdAt: "",
  completedAt: ""
});
const editFormRef = ref<FormInstance>();

const rules: FormRules = {
  proposerDept: [
    { required: true, message: "请选择提出部门", trigger: "change" }
  ],
  proposer: [{ required: true, message: "请输入提出人", trigger: "blur" }],
  category: [{ required: true, message: "请选择问题分类", trigger: "change" }],
  subject: [{ required: true, message: "请输入问题标的", trigger: "blur" }],
  description: [{ required: true, message: "请输入问题描述", trigger: "blur" }],
  owner: [{ required: true, message: "请输入责任人", trigger: "blur" }],
  ownerDept: [{ required: true, message: "请选择责任部门", trigger: "change" }],
  status: [{ required: true, message: "请选择进度", trigger: "change" }],
  createdAt: [{ required: true, message: "请选择提出时间", trigger: "change" }],
  completedAt: [
    {
      validator: (_r, v, cb) => {
        if ((editForm.status || "").toUpperCase() === "DONE" && !v)
          cb(new Error("完成状态需要填写完成时间"));
        else cb();
      },
      trigger: "change"
    }
  ],
  solution: [
    {
      validator: (_r, v, cb) => {
        if (
          (editForm.status || "").toUpperCase() === "DONE" &&
          (!v || !String(v).trim())
        ) {
          cb(new Error("完成状态需要填写解决描述"));
        } else cb();
      },
      trigger: "blur"
    }
  ]
};

function openEdit(row?: any) {
  Object.assign(
    editForm,
    row || {
      id: 0,
      proposerDept: "",
      proposer: "",
      category: "",
      subject: "",
      description: "",
      owner: "",
      ownerDept: "",
      solution: "",
      status: "Wait",
      createdAt: "",
      completedAt: ""
    }
  );
  editVisible.value = true;
}

async function saveEdit() {
  const valid = await editFormRef.value?.validate().catch(() => false);
  if (!valid) return;

  if (editForm.status.toUpperCase() === "DONE" && !editForm.completedAt) {
    ElMessage.warning("完成状态需要填写完成时间");
    return;
  }

  if (
    editForm.status.toUpperCase() === "DONE" &&
    editForm.completedAt < editForm.createdAt
  ) {
    ElMessage.warning("完成时间不能早于提出时间");
    return;
  }

  const payload: any = {
    proposerDept: editForm.proposerDept || null,
    proposer: editForm.proposer || null,
    category: editForm.category || null,
    subject: editForm.subject || null,
    description: editForm.description || null,
    owner: editForm.owner || null,
    ownerDept: editForm.ownerDept || null,
    solution: editForm.solution || null,
    status: (editForm.status || "").toUpperCase(),
    createdAt: editForm.createdAt || null,
    completedAt: editForm.completedAt ? editForm.completedAt : null
  };

  try {
    if (editForm.id && editForm.id !== 0) {
      await axios.put(
        `${apiBase}/${editForm.id}`,
        { id: editForm.id, ...payload },
        { headers: { "Content-Type": "application/json" } }
      );
      ElMessage.success("修改成功");
    } else {
      await axios.post(apiBase, payload, {
        headers: { "Content-Type": "application/json" }
      });
      ElMessage.success("新增成功");
    }
    editVisible.value = false;
    await fetchList();
  } catch (e: any) {
    handleHttpError(e);
  }
}

function handleHttpError(e: any) {
  const res = e?.response;
  if (!res) {
    ElMessage.error("网络异常或服务器不可达");
    return;
  }
  const pb = res.data || {};
  const lines: string[] = [];
  if (pb?.errors && typeof pb.errors === "object") {
    for (const [k, arr] of Object.entries(pb.errors)) {
      const msgs = Array.isArray(arr) ? (arr as any[]).join("；") : String(arr);
      const pretty =
        k === "req" ? "请求体" : (k as string).replace(/^\$\./, "");
      lines.push(`${pretty}: ${msgs}`);
    }
  }
  if (lines.length === 0) {
    if (pb?.title) lines.push(pb.title);
    if (pb?.detail) lines.push(pb.detail);
  }
  if (lines.length === 0) lines.push(`HTTP ${res.status} ${res.statusText}`);
  ElMessage.error(lines.join("\n"));
}

async function removeRow(id: number) {
  try {
    await axios.delete(`${apiBase}/${id}`);
    ElMessage.success("已删除");
    await fetchList();
  } catch (e: any) {
    handleHttpError(e);
  }
}

async function markDone(row: any) {
  if (!row.solution || !String(row.solution).trim() || !row.completedAt) {
    ElMessage.warning("请先填写“解决描述”再标记完成");
    // 打开编辑弹窗，预置为 DONE，引导用户填写，并触发表单规则
    openEdit({
      ...row,
      status: "done", // 将状态切到 DONE，让规则生效
      completedAt: row.completedAt || "" // 可让用户顺手选时间
    });
    return;
  }

  // 通过检查后，再走后端“标记完成”
  // const dateStr = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
  try {
    await axios.post(`${apiBase}/${row.id}/done`, null, {
      params: { completedAt: row.completedAt }
    });
    ElMessage.success("已标记完成");
    await fetchList();
  } catch (e: any) {
    handleHttpError(e);
  }
}

// 开始处理：Wait -> ONGOING
async function startProcessing(row: any) {
  try {
    await axios.post(`${apiBase}/${row.id}/start`);
    ElMessage.success("已开始处理");
  } catch (e: any) {
    if (e?.response && [404, 405].includes(e.response.status)) {
      try {
        const payload: any = {
          id: row.id,
          proposerDept: row.proposerDept ?? null,
          proposer: row.proposer ?? null,
          category: row.category ?? null,
          subject: row.subject ?? null,
          description: row.description ?? null,
          owner: row.owner ?? null,
          ownerDept: row.ownerDept ?? null,
          solution: row.solution ?? null,
          status: "ONGOING",
          createdAt: row.createdAt ?? null,
          completedAt: null
        };
        await axios.put(`${apiBase}/${row.id}`, payload, {
          headers: { "Content-Type": "application/json" }
        });
        ElMessage.success("已开始处理");
      } catch (err: any) {
        return handleHttpError(err);
      }
    } else {
      return handleHttpError(e);
    }
  }
  await fetchList();
}

const handleExport = async () => {
  loading.value = true;
  try {
    const response = await axios.get(API_ISSUE_TRACKER_EXPORT, {
      responseType: "blob"
    });

    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });

    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.download = `问题跟踪记录${new Date().toISOString().slice(0, 19).replace(/[-T:]/g, "")}.xlsx`;
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    ElMessage.error(
      error?.response?.data?.message ||
        error?.message ||
        "获取数据失败，请检查接口状态"
    );
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.p-6 {
  padding: 1.5rem;
}
.space-y-4 > * + * {
  margin-top: 1rem;
}
.flex {
  display: flex;
}
.items-center {
  align-items: center;
}
.gap-2 {
  gap: 0.5rem;
}
.gap-3 {
  gap: 0.75rem;
}
.w-40 {
  width: 10rem;
}
.w-44 {
  width: 11rem;
}
.w-52 {
  width: 13rem;
}
.w-72 {
  width: 18rem;
}
.ml-auto {
  margin-left: auto;
}
.mt-4 {
  margin-top: 1rem;
}
.justify-end {
  justify-content: flex-end;
}
.grid {
  display: grid;
}
.grid-cols-2 {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}
.col-span-2 {
  grid-column: span 2 / span 2;
}
</style>
